package com.zyx.flinkdemo.sql.func;

import com.zyx.flinkdemo.pojo.WaterSensor;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.ScalarFunction;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.call;

/**
 * @author zyx
 * @since 2021/5/30 16:58
 * desc: UDF(标量函数)实例
 */
public class UdfDemo {
    public static void main(String[] args) throws Exception {
        // 1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        // 2.读取端口数据创建流并转换每一行数据为JavaBean对象
        SingleOutputStreamOperator<WaterSensor> waterSensorDs = env
                .socketTextStream("linux201", 7777)
                .map(line -> {
                    String[] split = line.split(",");
                    return new WaterSensor(split[0],
                            Long.parseLong(split[1]),
                            Integer.parseInt(split[2]));
                });

        // 3.将流转换为表
        Table table = tableEnv.fromDataStream(waterSensorDs);
        tableEnv.createTemporaryView("water_sensor", table);

        // 4.使用未注册的udf
        /*table
                .select($("id"), call(MyLen.class, $("id")))
                .execute()
                .print();*/

        // 4.注册udf
        tableEnv.createTemporarySystemFunction("mylen", MyLen.class);

        // 5.使用udf
        // 使用TableAPI查询udf
        /*table
                .select($("id"), call("mylen", $("id")))
                .execute()
                .print();*/
        // 使用SQL查询udf
        tableEnv
                .sqlQuery("select id, mylen(id) from water_sensor")
                .execute()
                .print();

        // 6.执行任务
        env.execute();
    }

    public static class MyLen extends ScalarFunction {
        public int eval(String value) {
            return value.length();
        }
    }
}
